/*
 * $Id: AutoFitPanel.java 70 2009-04-21 13:04:31Z meyer@alphatec.de $
 * 
 *
 * Copyright 2009 DeltaDesk
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package deltadesk.gui.deltagui.widget;

import java.awt.Rectangle;

import deltadesk.gui.deltagui.graphics.GraphicsUtil;
import deltadesk.gui.deltagui.layout.AbstractLayout;

/**
 * AutoFitPanel.
 * 
 * @author Andreas Meyer
 * @version $Revision: 70 $
 */
public class AutoFitPanel extends SelfManagedPanel {

	/** The flag if the control should be scaled up. */
	private boolean scaleUp;


	/**
	 * Construct the panel.
	 * 
	 * @param url
	 */
	public AutoFitPanel(final Control control) {
		
		addDirect(control);
		setLayout(new AutoFitPanelLayout());
	}

	/**
	 * @param scaleUp the scaleUp to set
	 */
	public void setScaleUp(final boolean scaleUp) {
		this.scaleUp = scaleUp;
	}

	/**
	 * @see deltadesk.gui.deltagui.widget.Control#isFocusable()
	 */
	@Override
	public boolean isFocusable() {
		return false;
	}

	/**
	 * AutoFitPanelLayout
	 * 
	 * @author Andreas Meyer 
	 * @version $Revision: 70 $
	 */
	private class AutoFitPanelLayout extends AbstractLayout {

		/**
		 * @see deltadesk.gui.deltagui.layout.Layout#layout(deltadesk.gui.deltagui.widget.Composite)
		 */
		public boolean layout(final Composite widget) {
			
			if(!super.layout(widget)) {
				return false;
			}

			final Widget child = widget.get(0);
			final Rectangle newChildSize = GraphicsUtil.fitRectangleInto(
					widget.getWidth(),
					widget.getHeight(),
					child.getPreferredWidth(),
					child.getPreferredHeight(),
					scaleUp);

			child.setSize(newChildSize.width, newChildSize.height);
			child.setLocation(newChildSize.x, newChildSize.y);

			return true;
		}

	}

}
